<?php defined('BASEPATH') or exit('No direct script access allowed');

class Pay_pay_model extends CI_Model
{
    private  $alipay_config ;
    private  $wx_config ;
    public function __construct()
    {
        $this->sid = $GLOBALS['sid'];
        $this->data =$GLOBALS['config'];

        parent::__construct();
    }


    /**
     * 财付通支付模块
     * @param sp_billno    必填
     * @param total_fee    必填
     * @param desc    选填
     * @return array
     */

    public function _tenpay($sp_billno,$desc='',$total_fee,$order_id)
    {

        $this->load->library('tenpay/PayRequestHandler');
        $bargainor_id   = $this->config->item('tenpay_account','site');
        $key            =  $this->config->item('tenpay_key','site');
        $strDate        = date("Ymd");
        $strTime        = date("His");
        $randNum        = rand(1000, 9999);
        $strReq         = $strTime . $randNum;                        //10位序列号,可以自行调整
        $transaction_id = $bargainor_id . $strDate . $strReq; // 财付通交易单号，规则为：10位商户号+8位时间（YYYYmmdd)+10位流水号
        $return_url     = site_url('pay/index/tenpay_return_url/'.$order_id.'/');
        $total_fee      = $total_fee*100;                          // 商品价格（包含运费），以分为单位
        $reqHandler     = new PayRequestHandler();
        $reqHandler->init();
        $reqHandler->setKey($key);
        $reqHandler->setParameter("bargainor_id", $bargainor_id);			//商户号
        $reqHandler->setParameter("sp_billno", $sp_billno);					//商户订单号
        $reqHandler->setParameter("transaction_id", $transaction_id);		//财付通交易单号
        $reqHandler->setParameter("total_fee", $total_fee);					//商品总金额,以分为单位
        $reqHandler->setParameter("return_url", $return_url);				//返回处理地址
        $reqHandler->setParameter("desc", $desc);	//商品名称
        $reqHandler->setParameter("cs", "utf-8");
        //   $reqHandler->setParameter("spbill_create_ip", $_SERVER['REMOTE_ADDR']); //用户ip,测试环境时不要加这个ip参数，正式环境再加此参数
        $reqUrl = $reqHandler->getRequestURL();
        redirect($reqUrl);
    }


    /**
     * 支付宝支付模块
     * @param $out_trade_no   订单号        必填
     * @param $subject        订单名称      必填
     * @param $total_fee      总价         必填
     * @param $body           订单描述      选填
     * @param $show_url       商品展示地址   选填
     * @return $body
     */

    public function _alipay($out_trade_no,$subject,$total_fee,$body='',$show_url='',$order_id)
    {
        $alipay_config['partner']		= $this->data['alipay_id'];
        $alipay_config['key']			=  $this->data['alipay_key'];
        $alipay_config['sign_type']    = strtoupper('MD5');
        $alipay_config['input_charset']= strtolower('utf-8');
        $alipay_config['cacert']    = getcwd().'\\application\libraries\alipay\cacert.pem';
        $alipay_config['transport']    = 'http';
        $seller_email = $this->data['alipay_account'];
        $payment_type = "1";
        $notify_url = site_url('pay/index/alipay_return_url/'.$order_id.'/');
        $return_url = site_url('pay/index/alipay_return_url/'.$order_id.'/');
        $anti_phishing_key = "";
        $exter_invoke_ip = "";
        $parameter = array(
            "service" => "create_direct_pay_by_user",
            "partner" => trim($alipay_config['partner']),
            "payment_type"	=> $payment_type,
            "notify_url"	=> $notify_url,
            "return_url"	=> $return_url,
            "seller_email"	=> $seller_email,
            "out_trade_no"	=> $out_trade_no,
            "subject"	=> $subject,
            "total_fee"	=> $total_fee,
            "body"	=> $body,
            "show_url"	=> $show_url,
            "anti_phishing_key"	=> $anti_phishing_key,
            "exter_invoke_ip"	=> $exter_invoke_ip,
            "_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
        );
        $this->load->library('alipay/AlipaySubmit');
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get","确认");
        echo $html_text;
    }

    /**
     * 支付宝手机版支付模块
     * @param $out_trade_no   订单号        必填
     * @param $subject        订单名称      必填
     * @param $total_fee      总价         必填
     * @return $body
     */

    public function _alipay_m($out_trade_no,$subject,$total_fee,$order_id)
    {
        $alipay_config['partner']		= $this->data['alipay_id'];
        $alipay_config['key']			= $this->data['alipay_key'];
        $alipay_config['sign_type']     = strtoupper('MD5');;
        $alipay_config['input_charset'] = strtolower('utf-8');
        $alipay_config['cacert']    = getcwd().'\\application\libraries\alipay_m\cacert.pem';
        $alipay_config['transport']    = 'http';
        $seller_email = $this->data['alipay_account'];
        $format = "xml";  //返回格式
        $v = "2.0";   //返回格式
        $req_id = date('Ymdhis'); //请求号
        $notify_url =    site_url('mobile/pay/alipay_return_url/'.$order_id.'/');        //服务器异步通知页面路径
        $call_back_url = site_url('mobile/pay/alipay_return_url/'.$order_id.'/'); //页面跳转同步通知页面路径
        $merchant_url =  site_url('mobile/pay/alipay_return_url/'.$order_id.'/');          //操作中断返回地址

        //请求业务参数详细
        $req_data = '<direct_trade_create_req><notify_url>' . $notify_url . '</notify_url><call_back_url>' . $call_back_url . '</call_back_url><seller_account_name>' . $seller_email . '</seller_account_name><out_trade_no>' . $out_trade_no . '</out_trade_no><subject>' . $subject . '</subject><total_fee>' . $total_fee . '</total_fee><merchant_url>' . $merchant_url . '</merchant_url></direct_trade_create_req>';

//构造要请求的参数数组，无需改动
        $para_token = array(
            "service" => "alipay.wap.trade.create.direct",
            "partner" => trim($alipay_config['partner']),
            "sec_id" => trim($alipay_config['sign_type']),
            "format"	=> $format,
            "v"	=> $v,
            "req_id"	=> $req_id,
            "req_data"	=> $req_data,
            "_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
        );
        $this->load->library('alipay_m/AlipaySubmit');
        //建立请求
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestHttp($para_token);
        //URLDECODE返回的信息
        $html_text = urldecode($html_text);
        //解析远程模拟提交后返回的信息
        $para_html_text = $alipaySubmit->parseResponse($html_text);

        //获取request_token
        $request_token = $para_html_text['request_token'];

        //业务详细
        $req_data = '<auth_and_execute_req><request_token>' . $request_token . '</request_token></auth_and_execute_req>';


        //构造要请求的参数数组，无需改动
        $parameter = array(
            "service" => "alipay.wap.auth.authAndExecute",
            "partner" => trim($alipay_config['partner']),
            "sec_id" => trim($alipay_config['sign_type']),
            "format"	=> $format,
            "v"	=> $v,
            "req_id"	=> $req_id,
            "req_data"	=> $req_data,
            "_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
        );


        //建立请求
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter, 'get', '确认');
        echo $html_text;
    }

    /*
     * @desc 银联支付模块
     *
     * @param array $order_info 订单信息
     */
    public function _unionpay($order_info) {
        $this->load->library('unionpay/UnionPay');
        // 生产环境从数据库讯取
        //$unionpay_sign_cert_path = $_SERVER['DOCUMENT_ROOT']  . '/application/libraries/unionpay/700000000000001_acp.pfx';
        //$unionpay_sign_cert_pwd = '000000';
        $unionpay_sign_cert_path = BASEPATH . $GLOBALS['config']['unionpay_private_cert'];
        $unionpay_sign_cert_pwd = $GLOBALS['config']['unionpay_private_cert_pwd'];
        $merId = $GLOBALS['config']['unionpay_merchant_id'];

        $params = array(
            'version' => '5.0.0',				//版本号
            'encoding' => 'utf-8',				//编码方式
            'certId' => getSignCertId($unionpay_sign_cert_path, $unionpay_sign_cert_pwd),			//证书ID
            'txnType' => '01',				//交易类型
            'txnSubType' => '01',				//交易子类
            'bizType' => '000201',				//业务类型

            'frontUrl' => site_url('order/index/line_info?id='.$order_info['order_id']), //前台通知地址
            'backUrl' => site_url('/pay/index/unionpay_return_url/'.$order_info['order_id'].'/'), //后台通知地址


            'signMethod' => '01',		//签名方法
            'channelType' => check_wap() ? '08' : '07',		//渠道类型，07-PC，08-手机
            'accessType' => '0',		//接入类型
            'merId' => $merId,		        //商户代码，请改自己的测试商户号
            'orderId' => $order_info['order_sn'],	//商户订单号
            'txnTime' => date('YmdHis'),	//订单发送时间
            'txnAmt' => $order_info['txnAmt']*100,		//交易金额，单位分
            'currencyCode' => '156',	//交易币种
            'defaultPayType' => '0001',	//默认支付方式
            //'orderDesc' => '订单描述',  //订单描述，网关支付和wap支付暂时不起作用
            'reqReserved' =>' 测试', //请求方保留域，透传字段，查询、通知、对账文件中均会原样出现
        );

        $unionpay = new Unionpay();
        $unionpay->pay($params, $unionpay_sign_cert_path, $unionpay_sign_cert_pwd);
    }


}
